package com.erp.module.crm.xXCrm

import android.os.Handler
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.BaseActivity
import com.erp.activityKView.CrmFKView
import com.erp.bean.*
import com.erp.myAdapter.ClientPagerAdapter
import com.erp.util.Httputil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import kotlinx.android.synthetic.main.activity_client.*
import kotlinx.android.synthetic.main.header_knoya.view.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
 * Created by Administrator on 2016/11/12/012.
 * 作者：刘洋
 */
class ClientKActivity : BaseActivity(), View.OnClickListener, CrmFKView {


    companion object {
        private var id: String = ""
        fun getid(): String {
            return id
        }
    }
    lateinit var listfragment: MutableList<Fragment> //fragment集合
    lateinit var fragmentClientone: FragmentClientone
    lateinit var fragmentClienttwo: FragmentClienttwo
    lateinit var fragmentClientthree: FragmentClientthree
    lateinit var fragmentClientfour: FragmentClientfour
    lateinit var fragmentClientfive: FragmentClientfive
    lateinit var fragmentClientsix: FragmentClientsix
    lateinit var fragmentClientseven: FragmentClientseven
    lateinit var fragmentClienteight: FragmentClientseight
    lateinit var vpadapter: ClientPagerAdapter
    lateinit var clientDataBean: ClientDataBean//客户资料数据
    lateinit var clientGaugeBean: ClientGaugeBean//客户量尺信息
    lateinit var clientSchemeBean: ClientSchemeBean//方案的数据
    lateinit var clientContractBean: ClientContractBean//合同数据
    lateinit var clientAnzhaungBean: ClientAnzhaungBean//安装数据
    lateinit var clientShouhouBean: ClientShouhouBean//售后数据
    lateinit var jiaoliuBeanList: MutableList<ClientJiaoliuBean>//交流数据
    lateinit var updatedialog: AlertDialog
    private var name: String = ""
    private var zhuangtai: String = ""
    private var isnotify: Boolean = false
    private val a = "ClientActivity"

    private var joorder = ""
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_client
    }

    override fun initCreate() {
        initView()
        initData()
        initClick()
    }

    private fun initView() {
        id = intent.getStringExtra("id")
        clientDataBean = ClientDataBean()
        clientGaugeBean = ClientGaugeBean()
        clientSchemeBean = ClientSchemeBean()
        clientContractBean = ClientContractBean()
        clientAnzhaungBean = ClientAnzhaungBean()
        clientShouhouBean = ClientShouhouBean()
        fragmentClientone = FragmentClientone(clientDataBean, this, 2)
        fragmentClienttwo = FragmentClienttwo(this, clientGaugeBean)
        fragmentClientthree = FragmentClientthree(clientSchemeBean, this)
        fragmentClientfour = FragmentClientfour(clientContractBean, this)
        fragmentClientfive = FragmentClientfive()
        jiaoliuBeanList = ArrayList<ClientJiaoliuBean>()
        fragmentClientsix = FragmentClientsix(this, clientAnzhaungBean)
        fragmentClientseven = FragmentClientseven(this, clientShouhouBean)
        fragmentClienteight = FragmentClientseight(this, jiaoliuBeanList)
        listfragment = ArrayList()
        Header.tv_header_title.text = "客户详细资料"
        Header.iv_header_left.visibility = View.VISIBLE
        RgCrmKehu.isChecked = true
    }

    private fun initData() {
        listfragment = ArrayList()
        listfragment.add(fragmentClientone)
        listfragment.add(fragmentClienttwo)
        listfragment.add(fragmentClientthree)
        listfragment.add(fragmentClientfour)
        listfragment.add(fragmentClientfive)
        listfragment.add(fragmentClientsix)
        listfragment.add(fragmentClientseven)
        listfragment.add(fragmentClienteight)
        vpadapter = ClientPagerAdapter(supportFragmentManager, listfragment)
        VpCrm.adapter = vpadapter
        VpCrm.offscreenPageLimit = listfragment.size//设置缓存的Fragmnet的个数
        getclientdata()
    }

    private fun initClick() {
        RgCrmKehu.setOnClickListener(this)
        RgCrmLiangchi.setOnClickListener(this)
        RgCrmFangan.setOnClickListener(this)
        RgCrmHetong.setOnClickListener(this)
        RgCrmShengchandan.setOnClickListener(this)
        RgCrmAnzhuang.setOnClickListener(this)
        RgCrmShouhou.setOnClickListener(this)
        RgCrmJiaoliu.setOnClickListener(this)
        Header.iv_header_left.setOnClickListener(this)
        VpCrm.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) =
                    Unit

            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        HsvCrm.scrollTo(0, 0)
                        RgCrmKehu.isChecked = true
                    }
                    1 -> {
                        HsvCrm.scrollTo(RgCrm.width * 1 / 8, 0)
                        RgCrmLiangchi.isChecked = true
                    }
                    2 -> {
                        HsvCrm.scrollTo(RgCrm.width * 1 / 4, 0)
                        RgCrmFangan.isChecked = true
                    }
                    3 -> {
                        HsvCrm.scrollTo(RgCrm.width * 3 / 8, 0)
                        RgCrmHetong.isChecked = true
                    }
                    4 -> {
                        HsvCrm.scrollTo(RgCrm.width * 1 / 2, 0)
                        RgCrmShengchandan.isChecked = true
                    }
                    5 -> {
                        HsvCrm.scrollTo(RgCrm.width * 5 / 8, 0)
                        RgCrmAnzhuang.isChecked = true
                    }
                    6 -> {
                        HsvCrm.scrollTo(RgCrm.width * 3 / 4, 0)
                        RgCrmShouhou.isChecked = true
                    }
                    7 -> {
                        HsvCrm.scrollTo(RgCrm.width * 7 / 8, 0)
                        RgCrmJiaoliu.isChecked = true
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) = Unit
        })

    }

    override fun onClick(v: View) {
        when (v) {
            RgCrmKehu -> VpCrm.currentItem = 0
            RgCrmLiangchi -> VpCrm.currentItem = 1
            RgCrmFangan -> VpCrm.currentItem = 2
            RgCrmHetong -> VpCrm.currentItem = 3
            RgCrmShengchandan -> VpCrm.currentItem = 4
            RgCrmAnzhuang -> VpCrm.currentItem = 5
            RgCrmShouhou -> VpCrm.currentItem = 6
            RgCrmJiaoliu -> VpCrm.currentItem = 7
            Header.iv_header_left -> finish()
        }
    }

    private fun getclientdata() {
        updatedialog = Myutil.showupdatedialog(this@ClientKActivity, "正在加载", false)
        updatedialog.setOnKeyListener { dialog, keyCode, event ->
            finish()
            false
        }
        Httputil.getHttpClient(this, id, object : OnUserDataInterface {
            override fun onUserData(data: String) {
                Log.d("getHttpClient","date"+data)
                updatedialog.dismiss()
                getjsondata(data)

            }

            override fun onNot(throwable: String) {
                Log.d("getHttpClient","error"+throwable)
                if (Myutil.onerror(throwable, this@ClientKActivity)) {
                    Handler().postDelayed({ finish() }, 3000)
                }
                updatedialog.dismiss()
            }
        })
    }


    //客户详细资料的json解析
    fun getjsondata(data: String) {
        try {
            val jo = JSONObject(data)
            val joextension = JsonUtil.getjovolue(jo, "extension")
            val jocustomer = JsonUtil.getjovolue(joextension, "customer")
            val joproject = JsonUtil.getjovolue(joextension, "project")
            val jocontract = JsonUtil.getjovolue(joextension, "contract")
            val jostatus = JsonUtil.getjovolue(joextension, "status")
            val jsjiaoliu = JsonUtil.getjsvolue(joextension, "communication_log")
            zhuangtai = JsonUtil.getvolue(jostatus, "name")
            name = JsonUtil.getvolue(jocustomer, "name")
            joorder = JsonUtil.getvolue(joextension, "order")
            setclientdatabean(jo, jocustomer)
            clientDataBean.customer_name = JsonUtil.getvolue(jo, "shop_name")
            setcilentgauge(jo, joextension)
            setclentscheme(joproject)
            setclientcontract(jocontract)
            setanzhaung(jo)
            setshouhou(jo)
            setjiaoliu(jsjiaoliu)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("initdata","e="+e.toString())
        }
        updatedialog.dismiss()
        TvCrmName.text = name
        TvCrmZhuangtai.text = zhuangtai
        fragmentClientone.notifydata(clientDataBean)
        fragmentClienttwo.notifydata()
        fragmentClientthree.notifydata()
        fragmentClientfour.notifydata()
        fragmentClientfive.setdata(joorder)
        fragmentClientsix.notifydata()
        fragmentClientseven.notifydata()
        fragmentClienteight.notifydata(jiaoliuBeanList)
    }

    /**
     * 交流数据
     */
    @Throws(JSONException::class)
    private fun setjiaoliu(jsjiaoliu: JSONArray) {
        jiaoliuBeanList.clear()
        Log.d("TAAG",jsjiaoliu.toString())
        for (i in 0 until jsjiaoliu.length()) {
            val jiaoliubean = ClientJiaoliuBean()
            val jo = jsjiaoliu.get(i) as JSONObject
            jiaoliubean.relative_people = JsonUtil.getvolue(jo, "relative_people")
            jiaoliubean.content = JsonUtil.getvolue(jo, "content")
            jiaoliubean.appointment_communication = JsonUtil.getvolue(jo, "appointment_communication_time")
            jiaoliubean.communication_time = JsonUtil.getvolue(jo, "communication_time")
            jiaoliubean.id  = JsonUtil.getvolue(jo,"id")
            val listurl = ArrayList<String>()
            val listfid = ArrayList<String>()
            val listimg = ArrayList<ImgBean>()
            val js = JsonUtil.getjsvolue(jo, "attachment")
            if (js != null) {
                for (i in 0 until js.length()) {
                    val jo1 = js.get(i) as JSONObject
                    if (jo1.getString("filemime").indexOf("image") != -1) {
                        val imgbean = ImgBean()
                        imgbean.imgid = JsonUtil.getvolue(jo1, "fid")
                        imgbean.imguri = JsonUtil.getvolue(jo1, "uri")
                        imgbean.imgtime = JsonUtil.getvolue(jo1, "timestamp")
                        listimg.add(imgbean)
                    } else {
                        listfid.add(JsonUtil.getvolue(jo1, "fid"))
                        listurl.add(JsonUtil.getvolue(jo1, "uri"))
                    }
                }
            }
            jiaoliubean.uri = listurl
            jiaoliubean.listfileid = listfid
            jiaoliubean.listimg = listimg
            jiaoliuBeanList.add(jiaoliubean)
        }
    }

    /**
     * 售后数据解析
     */
    @Throws(JSONException::class)
    private fun setshouhou(jo: JSONObject) {
        val ss = ArrayList<String>()
        val jss = JsonUtil.getjsvolue(jo, "ass_people")
        if (jss != null) {
            for (i in 0 until jss.length()) {
                ss.add(jss.get(i) as String)
            }
        }
        val j=JsonUtil.getjsvolue(jo,"after_sales_server_obj")
        for(i in 0 until j.length()){
            val o= j[i] as JSONObject
            ss.add(JsonUtil.getvolue(o,"name"))
        }
        clientShouhouBean.ass_people = ss
        clientShouhouBean.ass_tel = JsonUtil.getvolue(jo, "ass_tel")
        clientShouhouBean.ass_start_time = JsonUtil.getvolue(jo, "ass_start_time")
        clientShouhouBean.ass_end_time = JsonUtil.getvolue(jo, "ass_end_time")
        clientShouhouBean.ass_asp = JsonUtil.getvolue(jo, "ass_asp")
        val listurl = ArrayList<String>()
        val listfid = ArrayList<String>()
        val listimg = ArrayList<ImgBean>()
        val js = JsonUtil.getjsvolue(jo, "ass_attachment")
        if (js != null) {
            for (i in 0 until js.length()) {
                val jo1 = js.get(i) as JSONObject
                listfid.add(JsonUtil.getvolue(jo1, "fid"))
                if (jo1.getString("filemime").indexOf("image") != -1) {
                    val imgbean = ImgBean()
                    imgbean.imgid = JsonUtil.getvolue(jo1, "fid")
                    imgbean.imguri = JsonUtil.getvolue(jo1, "uri")
                    imgbean.imgtime = JsonUtil.getvolue(jo1, "timestamp")
                    listimg.add(imgbean)
                } else {
                    var file = FileBean()
                    file.fid=JsonUtil.getvolue(jo1,"fid")
                    file.filename=JsonUtil.getvolue(jo1,"filename")
                    file.uri=JsonUtil.getvolue(jo1,"uri")
                    file.filemime=JsonUtil.getvolue(jo1,"filemime")
                    clientShouhouBean.listfile.add(file)
                }
            }
        }
        clientShouhouBean.uri = listurl
        clientShouhouBean.listfileid = listfid
        clientShouhouBean.listimg = listimg
    }

    /**
     * 安装数据解析
     */
    @Throws(JSONException::class)
    private fun setanzhaung(jo: JSONObject) {
        clientAnzhaungBean.isl_way = JsonUtil.getvolue(jo, "isl_way")
        val ss = ArrayList<String>()
        val jss = JsonUtil.getjsvolue(jo, "isl_people")
        if (jss != null) {
            for (i in 0 until jss.length()) {
                ss.add(jss.get(i) as String)
            }
        }
        val j=JsonUtil.getjsvolue(jo,"installer_obj")
        for(i in 0 until j.length()){
            val o= j[i] as JSONObject
            ss.add(JsonUtil.getvolue(o,"name"))
        }
        clientAnzhaungBean.isl_people = ss
        clientAnzhaungBean.isl_tel = JsonUtil.getvolue(jo, "isl_tel")
        clientAnzhaungBean.isl_start_time = JsonUtil.getvolue(jo, "isl_start_time")
        clientAnzhaungBean.isl_end_time = JsonUtil.getvolue(jo, "isl_end_time")
        clientAnzhaungBean.isl_asp = JsonUtil.getvolue(jo, "isl_asp")
        clientAnzhaungBean.return_visit_time = JsonUtil.getvolue(jo, "return_visit_time")
        clientAnzhaungBean.return_visit_content = jo.getString("return_visit_content")
        clientAnzhaungBean.return_visit_content = JsonUtil.getvolue(jo, "return_visit_content")
        val listurl = ArrayList<String>()
        val listfid = ArrayList<String>()
        val listimg = ArrayList<ImgBean>()
        val listfile = ArrayList<FileBean>()
        val js = JsonUtil.getjsvolue(jo, "isl_attachment")
        if (js != null) {
            for (i in 0 until js.length()) {
                val jo1 = js.get(i) as JSONObject
                listfid.add(JsonUtil.getvolue(jo1, "fid"))
                if (jo1.getString("filemime").indexOf("image") != -1) {
                    val imgbean = ImgBean()
                    imgbean.imgid = JsonUtil.getvolue(jo1, "fid")
                    imgbean.imguri = JsonUtil.getvolue(jo1, "uri")
                    imgbean.imgtime = JsonUtil.getvolue(jo1, "timestamp")
                    listimg.add(imgbean)
                } else {
                    var file = FileBean()
                    file.fid=JsonUtil.getvolue(jo1,"fid")
                    file.filename=JsonUtil.getvolue(jo1,"filename")
                    file.uri=JsonUtil.getvolue(jo1,"uri")
                    file.filemime=JsonUtil.getvolue(jo1,"filemime")
                    listfile.add(file)
                }
            }
        }
        clientAnzhaungBean.listfile = listfile
        clientAnzhaungBean.uri = listurl
        clientAnzhaungBean.listimgbean = listimg
        clientAnzhaungBean.listfid = listfid
    }

    //合同数据
    @Throws(JSONException::class)
    private fun setclientcontract(jocontract: JSONObject) {
        clientContractBean.contract_num = JsonUtil.getvolue(jocontract, "contract_num")
        clientContractBean.registration_time = JsonUtil.getvolue(jocontract, "registration_time")
        clientContractBean.amount = JsonUtil.getvolue(jocontract, "amount")
        clientContractBean.promis_delivery_time = JsonUtil.getvolue(jocontract, "promis_delivery_time")
        clientContractBean.yudinganzhuang_time = JsonUtil.getvolue(jocontract, "yudinganzhuang_time")
        clientContractBean.reason = JsonUtil.getvolue(jocontract, "reason")
        clientContractBean.remark = JsonUtil.getvolue(jocontract, "remark")
    }


    //量尺信息
    @Throws(JSONException::class)
    private fun setcilentgauge(jo: JSONObject, joextension: JSONObject?) {
//        val filelist = ArrayList<String>()
//        val listimg = ArrayList<ImgBean>()
        val listfid = ArrayList<String>()
        val listphoto = ArrayList<PhotoBean>()
        val listfile = ArrayList<FileBean>()
        val jsmsa = JsonUtil.getjsvolue(joextension, "msa_attachment")
        if (jsmsa != null) {
            for (i in 0 until jsmsa.length()) {
                val jomsa = jsmsa.getJSONObject(i)
                listfid.add(JsonUtil.getvolue(jomsa, "fid"))
//                if (jomsa.getString("filemime").indexOf("image") != -1) {
//                    val imgbean = ImgBean()
//                    imgbean.imgid = JsonUtil.getvolue(jomsa, "fid")
//                    imgbean.imguri = JsonUtil.getvolue(jomsa, "uri")
//                    imgbean.imgtime = JsonUtil.getvolue(jomsa, "timestamp")
//                    listimg.add(imgbean)
//                } else {
//                    filelist.add(JsonUtil.getvolue(jomsa, "uri"))
//                }
                var filemime = JsonUtil.getvolue(jomsa, "filemime")
                if(filemime=="image/jpeg"){
                    var photo = PhotoBean()
                    photo.fid=JsonUtil.getvolue(jomsa,"fid")
                    photo.filename=JsonUtil.getvolue(jomsa,"filename")
                    photo.uri=JsonUtil.getvolue(jomsa,"uri")
                    photo.timestamp=JsonUtil.getvolue(jomsa,"timestamp")
                    listphoto.add(photo)
                }else{
                    var file = FileBean()
                    file.fid=JsonUtil.getvolue(jomsa,"fid")
                    file.filename=JsonUtil.getvolue(jomsa,"filename")
                    file.uri=JsonUtil.getvolue(jomsa,"uri")
                    file.filemime=filemime
                    listfile.add(file)
                }
            }
        }
        clientGaugeBean.listphoto = listphoto
        clientGaugeBean.listfile = listfile
        clientGaugeBean.listfid = listfid
//        clientGaugeBean.filelist = filelist
//        clientGaugeBean.listimgbean = listimg
        clientGaugeBean.addr = JsonUtil.getvolue(jo, "addr")
        clientGaugeBean.appointment_measuring_time = JsonUtil.getvolue(jo, "appointment_measuring_time")
        clientGaugeBean.measuring_time = JsonUtil.getvolue(jo, "measuring_time")
        clientGaugeBean.remeasuring_time = JsonUtil.getvolue(jo, "remeasuring_time")
        val jsshejishi = JsonUtil.getjsvolue(jo, "designer_obj")
        Log.d("shejishi=",jsshejishi.toString())
        val listshejishi = ArrayList<String>()
        if (jsshejishi != null) {
            for (i in 0 until jsshejishi.length()) {
                val joshejishi = jsshejishi.getJSONObject(i)
                listshejishi.add(joshejishi.getString("name"))
            }
        }
        clientGaugeBean.shejishi = listshejishi
    }
    //方案数据
    @Throws(JSONException::class)
    private fun setclentscheme(jocustomer: JSONObject) {
        Log.d("setclentscheme","jocustomer="+jocustomer.toString())
        val jsmsa = JsonUtil.getjsvolue(jocustomer, "attachment")
        val filelist = ArrayList<String>()
        val listimg = ArrayList<ImgBean>()
        val listfid = ArrayList<String>()
        val listfile = ArrayList<FileBean>()
        if (jsmsa != null) {
            for (i in 0 until jsmsa.length()) {
                val jomsa = jsmsa.getJSONObject(i)
                listfid.add(JsonUtil.getvolue(jomsa, "fid"))
                if (jomsa.getString("filemime").indexOf("image") != -1) {
                    val imgbean = ImgBean()
                    imgbean.imgid = JsonUtil.getvolue(jomsa, "fid")
                    imgbean.imguri = JsonUtil.getvolue(jomsa, "uri")
                    imgbean.imgtime = JsonUtil.getvolue(jomsa, "timestamp")
                    listimg.add(imgbean)
                } else {
                    var file = FileBean()
                    file.fid=JsonUtil.getvolue(jomsa,"fid")
                    file.filename=JsonUtil.getvolue(jomsa,"filename")
                    file.uri=JsonUtil.getvolue(jomsa,"uri")
                    file.filemime=JsonUtil.getvolue(jomsa,"filemime")
                    listfile.add(file)
                }
            }
        }
        clientSchemeBean.listfile = listfile
        clientSchemeBean.listfid = listfid
        clientSchemeBean.filelist = filelist
        clientSchemeBean.listimgbean = listimg
        clientSchemeBean.description = JsonUtil.getvolue(jocustomer,"description")
    }

    //客户资料
    @Throws(JSONException::class)
    private fun setclientdatabean(jo: JSONObject, jocustomer: JSONObject) {
        clientDataBean.name = JsonUtil.getvolue(jocustomer, "name")
        clientDataBean.tel = JsonUtil.getvolue(jocustomer, "tel")
        clientDataBean.sex = JsonUtil.getvolue(jocustomer, "sex")
        clientDataBean.demand = JsonUtil.getvolue(jocustomer, "demand")
        clientDataBean.occupation = JsonUtil.getvolue(jocustomer, "occupation")
        clientDataBean.kehulaiyuan = JsonUtil.getvolue(jocustomer, "kehulaiyuan")
        clientDataBean.store_manager_name = JsonUtil.getvolue(jo, "store_manager_name")
        clientDataBean.age = JsonUtil.getvolue(jocustomer, "age")
        clientDataBean.wechat_number = JsonUtil.getvolue(jocustomer, "wechat_number")
        clientDataBean.customer_cat = JsonUtil.getvolue(jocustomer,"customer_cat")
        clientDataBean.exclusive_shop = JsonUtil.getvolue(jocustomer,"exclusive_shop")
        val jsxiaoshouyuan = JsonUtil.getjsvolue(jo, "xiaoshouyuan_obj")
        val listxiaoshouyuan = ArrayList<String>()
        if (jsxiaoshouyuan != null) {
            for (i in 0 until jsxiaoshouyuan.length()) {
                val joshejishi = jsxiaoshouyuan.getJSONObject(i)
                listxiaoshouyuan.add(JsonUtil.getvolue(joshejishi, "name"))
            }
        }
        clientDataBean.xiaoshouyuan = listxiaoshouyuan
        clientDataBean.remark = JsonUtil.getvolue(jocustomer, "remark")
    }

    override fun updata(s: String) {
        getjsondata(s)
        isnotify = true
    }
    }
